import * as dd from 'dingtalk-jsapi';
import crypto from 'crypto';
import { Toast } from 'antd-mobile';
const { NODE_ENV } = process.env
const config = {
  signKey: '***********',
  corpId: '***********',
  
};

const md5For = str =>
  crypto
    .createHash('md5')
    .update(str)
    .digest('hex');

/**
 * 构建密钥
 * @param {*} params
 */
const signFor = params => {
  const newParams = {
    ...params,
    sign_key: config.signKey,
  };
  const keys = Object.keys(newParams);
  keys.sort();
  const text = keys.reduce((pre, key, index) => {
    const value = newParams[key];
    if (!index) {
      return `${key}=${value}`;
    }
    return `${pre}&${key}=${value}`;
  }, '');
  return md5For(text);
};

/**
 * 构建带密钥的url
 * @param {string} url
 * @param {object} params
 */
const signUrlFor = (url, params = {}) => {
  const d = { ...params, timestamp: Date.now() };
  return Object.entries(d).reduce(
    (pre, [key, val]) => `${pre}&${key}=${val}`,
    `${url}?sign=${signFor(d)}`,
  );
};

/**
 * auth.code => duc => 埋入cookie
 */
const auth = () => {
  return new Promise((resolve, reject) => {
    if (dd.env.platform !== 'notInDingTalk') {
      // dd.ready(async () => {
      //   alert(2)
      //   const auth = await dd.runtime.permission.requestAuthCode({
      //     corpId: 'dingfc0e67ed7f6ac93d',//config.corpId,
      //   });
      
      // });
      dd.ready(function() {
        // dd.ready参数为回调函数，在环境准备就绪时触发，jsapi的调用需要保证在该回调函数触发后调用，否则无效。
        dd.runtime.permission.requestAuthCode({
            corpId: config.corpId,
            onSuccess: function(auth) {
              fetch(signUrlFor('/api/v1/duc/auth/eapp_login'), {
                method: 'post',
                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                body: JSON.stringify({ authCode: auth.code }),
              }).then(async raw => {
                const res = await raw.json();
                window.document.cookie = Array.isArray(res.specSetCookie) ? res.specSetCookie[0].split('domain=.dtwave-inc.com; httponly')[0]
                : res.specSetCookie.split('domain=.dtwave-inc.com; httponly')[0]
                resolve()
                })
              .catch(err => {
                alert('登录失败')
                Toast.offline(`登录失败`);
                reject(err);
              });
            },
            onFail : function(err) {
              alert('接口调用失败，请在钉钉中访问')
            }
      
        });
    });
    } else {
      alert('缺少钉钉环境')
      resolve();
    }
  });
};

export default auth();
